package com.topcent.tioxyc.consumer;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.pojo.*;
import com.topcent.tioxyc.pojo.vo.*;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.topcent.tioxyc.util.PurchaseCommunity;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 陈百万
 * @date: 2025/11/12 14:28
 * @Description: 付款单-陈百万改造最新逻辑
 */
@Component
@RabbitListener(queues = "FuKuanDanNew")
@Slf4j
public class FuKuanDanNewConsumer {

    private static final String DATA_CREATE = "data_create";
    private static final String DATA_UPDATE = "data_update";

    @RabbitHandler
    public void handleMessage(String msg, Channel channel, Message message) throws IOException {
        try {
            // 在这里处理推送来的数据
            JSONObject payloadJSON = JSONUtil.parseObj(msg);
            String op = payloadJSON.getStr("op");
            String data = payloadJSON.getStr("data");

            if (DATA_UPDATE.equals(op)) {
                dates(data); // 计算审核完成的时间
            }else if (DATA_CREATE.equals(op)) {
                changeYu(data); // 处理预付款
                update(data); // 处理尾款
            }

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            System.out.println("Message acknowledged");
        } catch (Exception e) {
            // 处理异常并拒绝消息
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            System.err.println("发送消息失败，重试中 " + e.getMessage());
        }
    }

    // 处理付款单开始时预付款，更改拷贝数据表的数据
    private void changeYu(String data) {
        Header[] headers = ConnmeUtils.createHeaders();
        Fukuandan fukuandan = JSONUtil.toBean(data, Fukuandan.class);
        if (fukuandan.get_widget_1721546510495()==null) {
            return;
        }
        Map<String, Map<String, Double>> yushou = new HashMap<>();

        for (Fukuandan.Yufu yufu : fukuandan.get_widget_1721546510495()) {
            if (yushou.containsKey(yufu.get_widget_1721546510504())) {
                Map<String, Double> stringDoubleMap = yushou.get(yufu.get_widget_1721546510504());
                if (stringDoubleMap.containsKey(yufu.get_widget_1721616942683())) {
                    Double aDouble = yushou.get(yufu.get_widget_1721546510504()).get(yufu.get_widget_1721616942683());
                    stringDoubleMap.put(yufu.get_widget_1721616942683(), yufu.get_widget_1721546510520() + aDouble);
                } else {
                    stringDoubleMap.put(yufu.get_widget_1721616942683(), yufu.get_widget_1721546510520());
                }
            } else {
                Map<String, Double> yushou001 = new HashMap<>();
                yushou001.put(yufu.get_widget_1721616942683(), yufu.get_widget_1721546510520());
                yushou.put(yufu.get_widget_1721546510504(), yushou001);
            }
        }
        chuliYuSuan(headers, yushou);
    }

    // 修改付款单时间信息
    private void dates(String data) {
        Lin lin = JSONUtil.toBean(data, Lin.class);
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameterDelete = new HashMap<>();
        parameterDelete.put("instance_id", lin.get_id());
        parameterDelete.put("tasks_type", 1);
        String jsonSale = JSONUtil.toJsonStr(parameterDelete);
        JSONObject jdySale = ApiClient.sendPostRequest("https://api.jiandaoyun.com/api/v5/workflow/instance/get", headers, jsonSale);
        JdyPurchaseOrder jdyPurchaseOrder = JSONUtil.toBean(jdySale, JdyPurchaseOrder.class);
        if (jdyPurchaseOrder.getStatus() == 1) {
            int size = jdyPurchaseOrder.getTasks().size() - 1;
            boolean d=true;
            boolean c=true;
            for (int i = size; i > 0; i--) {
                if (  jdyPurchaseOrder.getTasks().get(i).getFlow_name().equals("财务审核") &&
                        jdyPurchaseOrder.getTasks().get(i).getFinish_action().equals("forward")&& d){
                    lin.set_widget_1736231012617(jdyPurchaseOrder.getTasks().get(i).getFinish_time());
                    d=false;
                }
                if (jdyPurchaseOrder.getTasks().get(i).getFlow_name().equals("财务审核") &&
                        jdyPurchaseOrder.getTasks().get(i).getFinish_action().equals("forward") && c){
                    lin.set_widget_1736231012618(jdyPurchaseOrder.getTasks().get(i).getCreate_time());
                    c=false;
                }
            }
            Map<String, Object> parameterInster = new HashMap<>();
            parameterInster.put("app_id", "66a0c3efcd4dd2a1c8a4a13f");
            // 付款单页面：669cb70dab60aa3f4a7bb8b2
            parameterInster.put("entry_id", "669cb70dab60aa3f4a7bb8b2");
            parameterInster.put("is_start_trigger", "true");
            parameterInster.put("data_id", lin.get_id());
            lin.set_id(null);
            parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(lin));
            String jsonSalee = JSONUtil.toJsonStr(parameterInster);
            ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
        }
    }

    // 对采购订单_拷贝数据（陈志生）表的数据更改 【已付金额、未付金额】预付款
    private void chuliYuSuan(Header[] headers, Map<String, Map<String, Double>> weikuan) {
        weikuan.forEach((key, innerMap) -> {
            try {
                Map<String, Object> parameterCxv = new HashMap<>();
                parameterCxv.put("app_id", "6690c7633df0f4b90b4ef551");
                parameterCxv.put("entry_id", "669df675b02f2a74e35ca2f9");
                //采购订单_拷贝数据（陈志生）669df675b02f2a74e35ca2f9
                innerMap.forEach((innerKey, value) -> {
                    HashMap<String, String> communti = new HashMap<>();

                    communti.put("_widget_1721628277543", key);
                    communti.put("_widget_1721628277558", innerKey);
                    List<SAPPurchaseOrder> sapPurchaseOrders = PurchaseCommunity.queryBased(parameterCxv, headers, communti, SAPPurchaseOrder.class);

                    SAPPurchaseOrder salesOrderKu = sapPurchaseOrders.getFirst();
                    if (salesOrderKu == null) {
                        return;
                    }
                    if (sapPurchaseOrders.getFirst().get_widget_1722475785243() != null) {
                        sapPurchaseOrders.getFirst().set_widget_1722475785243(sapPurchaseOrders.getFirst().get_widget_1722475785243() + value);
                    } else {
                        sapPurchaseOrders.getFirst().set_widget_1722475785243(value);
                    }
                    // 累计预付款
                    sapPurchaseOrders.getFirst().set_widget_1722475785244((sapPurchaseOrders.getFirst().get_widget_1722475785244() != null) ? sapPurchaseOrders.getFirst().get_widget_1722475785244() : 0.0 + value);
                    BigDecimal subtract = sapPurchaseOrders.getFirst().get_widget_1731911494439().subtract(BigDecimal.valueOf(sapPurchaseOrders.getFirst().get_widget_1722475785243()));
                    sapPurchaseOrders.getFirst().set_widget_1731911494439(subtract); // 计算赋值未付金额

                    if(subtract.compareTo(BigDecimal.valueOf(-1)) < 0){
                        return;
                    }

                    Map<String, Object> parameterInster = new HashMap<>();
                    parameterInster.put("app_id", "6690c7633df0f4b90b4ef551");
                    //采购订单_拷贝数据（陈志生）669df675b02f2a74e35ca2f9
                    parameterInster.put("entry_id", "669df675b02f2a74e35ca2f9");
                    parameterInster.put("is_start_trigger", "true");
                    parameterInster.put("data_id", sapPurchaseOrders.getFirst().get_id());
                    sapPurchaseOrders.getFirst().set_id(null);
                    parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(sapPurchaseOrders.getFirst()));
                    String jsonSale = JSONUtil.toJsonStr(parameterInster);
                    ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSale);
                });
            } catch (Exception e) {
                log.error("Error processing key: {}", key, e);
            }
        });
    }

    // 修改入库凭证【已付总金额、未付金额、尾款未付总金额】and 对采购订单_拷贝数据（陈志生）表的数据更改 【已付金额、未付金额】尾款
    private void update(String data) {
        PaymentForm paymentForm = JSONUtil.toBean(data, PaymentForm.class);
        Header[] headers = ConnmeUtils.createHeaders();

        if (paymentForm.get_widget_1721548605263()==null) {
            return;
        }

        /*Map<String, Object> parameterDelete = new HashMap<>();
        parameterDelete.put("instance_id", paymentForm.get_id());
        parameterDelete.put("tasks_type", 1);
        String jsonSale = JSONUtil.toJsonStr(parameterDelete);
        JSONObject jdySale = ApiClient.sendPostRequest("https://api.jiandaoyun.com/api/v5/workflow/instance/get", headers, jsonSale);
        JdyPurchaseOrder jdyPurchaseOrder = JSONUtil.toBean(jdySale, JdyPurchaseOrder.class);
        if (jdyPurchaseOrder.getStatus() == 1) {*/
        // OrderFinalPayment：订单尾款列表
        for (PaymentForm.OrderFinalPayment orderFinalPayment : paymentForm.get_widget_1721548605263()) {
            if (orderFinalPayment.get_widget_1727334556949() == null || orderFinalPayment.get_widget_1727334556949().isEmpty() ||
                    orderFinalPayment.get_widget_1721548605264() == null || orderFinalPayment.get_widget_1721548605264().isEmpty()
                    || orderFinalPayment.get_widget_1721548605265()==null || orderFinalPayment.get_widget_1721548605267() == 0 || orderFinalPayment.get_widget_1721548605266().compareTo(BigDecimal.ZERO) == 0) {
                continue; // 跳过当前遍历
            }
            BigDecimal orderFinalPaidAmount = orderFinalPayment.get_widget_1721548605266(); // 付款单尾款的付款金额

            Map<String, Object> parameterCxv = new HashMap<>();
            parameterCxv.put("app_id", "66a0c3efcd4dd2a1c8a4a13f");
            // 入库凭证：66a3727ee9d0a8542c969091     通过入库单and发票编号查询
            parameterCxv.put("entry_id", "66a3727ee9d0a8542c969091");
            HashMap<String, String> communti = new HashMap<>();
            communti.put("_widget_1727315685608", orderFinalPayment.get_widget_1727334556949());
            communti.put("_widget_1721987711273", orderFinalPayment.get_widget_1721548605264());
            // 只会有一条入库凭证单数据
            List<InvoiceDocument> invoiceDocuments = PurchaseCommunity.queryBased(parameterCxv, headers, communti, InvoiceDocument.class);
            if (invoiceDocuments == null || invoiceDocuments.isEmpty()) {
                continue; // 跳过当前遍历
            }

            InvoiceDocument document = invoiceDocuments.getFirst();
            // lineItems : 入库单：明细表
            List<InvoiceDocument.InvoiceLineItem> lineItems = document.get_widget_1727340673732();

            // 1. 计算所有行项目的含税金额总和
            BigDecimal totalAmount = lineItems.stream()
                    .map(InvoiceDocument.InvoiceLineItem::get_widget_1727340673745)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            if (totalAmount.compareTo(BigDecimal.ZERO) == 0) { // 总金额为0时跳过
                continue;
            }

            // 获取尾款占比
            //BigDecimal finalPaymentRate = BigDecimal.valueOf(orderFinalPayment.get_widget_1721548605265());

            // 定义变量用于存储分摊金额总和和未付金额总和
            BigDecimal totalAllocationAmount = BigDecimal.ZERO;  // 已付总金额
            BigDecimal totalUnpaidAmount = BigDecimal.ZERO;  // 未付总金额
            BigDecimal totalBalanceAmount = BigDecimal.ZERO;   // 尾款未付总金额
                /*if(document.get_widget_1731638214170()!=null && document.get_widget_1731638214170().compareTo(BigDecimal.ZERO) <= 0){
                    continue;
                }*/

            for (InvoiceDocument.InvoiceLineItem invoiceLineItem : lineItems) {
                // 行项目含税金额
                BigDecimal lineItemAmount = invoiceLineItem.get_widget_1727340673745();
                if (lineItemAmount == null || lineItemAmount.compareTo(BigDecimal.ZERO) == 0) {
                    continue;
                }
                //把其他采购订单的付款金额拿过来。
                Map<String, Object> cgdd = new HashMap<>();
                cgdd.put("app_id", "6690c7633df0f4b90b4ef551");
                //采购订单_拷贝数据（陈志生）669df675b02f2a74e35ca2f9
                cgdd.put("entry_id", "669df675b02f2a74e35ca2f9");

                communti.put("_widget_1721628277543", invoiceLineItem.get_widget_1727340673739());
                communti.put("_widget_1721628277558", invoiceLineItem.get_widget_1727340673735());
                // sapPurchaseOrders是只有一条数据
                List<SAPPurchaseOrder> sapPurchaseOrders = PurchaseCommunity.queryBased(cgdd, headers, communti, SAPPurchaseOrder.class);
                // 含税金额不能为空
                if (sapPurchaseOrders.isEmpty() || sapPurchaseOrders.getFirst() == null ||
                        sapPurchaseOrders.getFirst().get_widget_1724225500094() == null) {
                    continue;
                }
                    /*if(sapPurchaseOrders.getFirst().get_widget_1731911494439()!=null && sapPurchaseOrders.getFirst().get_widget_1731911494439().compareTo(BigDecimal.ZERO) <= 0){
                        continue;
                    }*/

                // 如果采购订单查询结果不为空，取出已付金额
                BigDecimal paidAmount = sapPurchaseOrders.getFirst().get_widget_1722475785243() == null
                        ? BigDecimal.ZERO
                        : BigDecimal.valueOf(sapPurchaseOrders.getFirst().get_widget_1722475785243());

                // 计算分摊比例（保留10位小数，避免精度损失）
                BigDecimal allocationRatio = lineItemAmount.divide(totalAmount, 10, RoundingMode.HALF_UP);

                // 计算尾款分摊金额 计算分摊金额（保留10位小数，支持负数）
                BigDecimal allocationAmount = orderFinalPaidAmount.multiply(allocationRatio).setScale(10, RoundingMode.HALF_UP);

                // 3. 累加已有分摊金额（处理历史数据）
                BigDecimal existingAllocationAmount = invoiceLineItem.get_widget_1731575068806();
                if (existingAllocationAmount != null) {
                    allocationAmount = allocationAmount.add(existingAllocationAmount);
                }

                // 明细表.已付金额
                invoiceLineItem.set_widget_1731575068806(allocationAmount);

                // 计算未付金额 unpaidAmount
                BigDecimal zongshu = invoiceLineItem.get_widget_1727340673745();
                //隐藏.add(sapPurchaseOrders.getFirst().get_widget_1724225500094());

                BigDecimal unpaidAmount = zongshu
                        .subtract(allocationAmount)
                        .subtract(paidAmount)
                        .setScale(10, RoundingMode.HALF_UP);

                // 明细表.未付金额
                invoiceLineItem.set_widget_1731575068807(unpaidAmount);


                // 计算分摊总金额累加值：已付金额减去未付金额，加上当前行的分摊金额
                BigDecimal allocationAdjustment = paidAmount.add(allocationAmount);

                // 累加到分摊金额总和和未付金额总和
                totalAllocationAmount = totalAllocationAmount.add(allocationAdjustment);
                totalUnpaidAmount = totalUnpaidAmount.add(unpaidAmount);
                totalBalanceAmount = totalBalanceAmount.add(invoiceLineItem.get_widget_1727340673745().subtract(allocationAmount));

                // 未付金额为负数就不操作
                if(unpaidAmount.compareTo(BigDecimal.valueOf(-1)) < 0){
                    continue;
                }
                // 处理尾款的采购订单_拷贝数据表逻辑 669df675b02f2a74e35ca2f9
                sapPurchaseOrders.getFirst().set_widget_1722475785243(allocationAdjustment.setScale(2, RoundingMode.HALF_UP).doubleValue());
                sapPurchaseOrders.getFirst().set_widget_1731911494439(unpaidAmount);
                sapPurchaseOrders.getFirst().set_widget_1722475785245(allocationAmount.setScale(2, RoundingMode.HALF_UP).doubleValue());

                log.info("付款单到采购订单_拷贝数据===>{},行:{},已付金额：{},未付金额:{}", sapPurchaseOrders.getFirst().get_widget_1721628277543(), sapPurchaseOrders.getFirst().get_widget_1721628277558() , sapPurchaseOrders.getFirst().get_widget_1722475785243(),sapPurchaseOrders.getFirst().get_widget_1731911494439());
                Map<String, Object> parameterEnd = new HashMap<>();
                parameterEnd.put("app_id", "6690c7633df0f4b90b4ef551");
                //采购订单_拷贝数据（陈志生）669df675b02f2a74e35ca2f9
                parameterEnd.put("entry_id", "669df675b02f2a74e35ca2f9");
                parameterEnd.put("is_start_trigger", "true");
                parameterEnd.put("data_id", sapPurchaseOrders.getFirst().get_id());
                sapPurchaseOrders.getFirst().set_id(null);
                parameterEnd.put("data", ConnmeUtils.convertEntityToMapNull(sapPurchaseOrders.getFirst()));
                String jsonSaleEnd = JSONUtil.toJsonStr(parameterEnd);
                ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSaleEnd);
            }

            // 输出分摊金额总和和未付金额总和到总记录
                /*BigDecimal existingTotalAllocationAmount = invoiceDocuments.getFirst().get_widget_1731638214169();
                BigDecimal existingTotalUnpaidAmount = invoiceDocuments.getFirst().get_widget_1731638214170();

                if (existingTotalAllocationAmount != null) {
                    totalAllocationAmount = totalAllocationAmount.add(existingTotalAllocationAmount);
                }
                if (existingTotalUnpaidAmount != null) {
                    totalUnpaidAmount = totalUnpaidAmount.add(existingTotalUnpaidAmount);
                }*/

            // 未付金额为负数就不操作
            if(totalUnpaidAmount.compareTo(BigDecimal.valueOf(-1)) < 0){
                continue;
            }
            invoiceDocuments.getFirst().set_widget_1731638214169(totalAllocationAmount);
            invoiceDocuments.getFirst().set_widget_1731638214170(totalUnpaidAmount);
            invoiceDocuments.getFirst().set_widget_1731915520417(totalBalanceAmount);

            log.info("付款单到入库凭证===>{},发票编号:{},已付总金额：{},未付总金额:{}", invoiceDocuments.getFirst().get_widget_1727315685608(), invoiceDocuments.getFirst().get_widget_1721987711273() , invoiceDocuments.getFirst().get_widget_1731638214169(), invoiceDocuments.getFirst().get_widget_1731638214170());
            Map<String, Object> parameterInster = new HashMap<>();
            parameterInster.put("app_id", "66a0c3efcd4dd2a1c8a4a13f");
            // 入库凭证：66a3727ee9d0a8542c969091
            parameterInster.put("entry_id", "66a3727ee9d0a8542c969091");
            parameterInster.put("is_start_trigger", "true");
            parameterInster.put("data_id", invoiceDocuments.getFirst().get_id());
            invoiceDocuments.getFirst().set_id(null);
            parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(invoiceDocuments.getFirst()));
            String jsonSalee = JSONUtil.toJsonStr(parameterInster);
            ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
        }
        //}
    }


}
